using UnityEngine;

namespace BehaviorDesigner.Runtime.Tasks
{
    [TaskDescription("Just walking around")]
    [TaskCategory("Custom")]
    public class ActionPatrol : Action
    {
        [Tooltip("The waypoints to patrol")]
        public Transform[] waypoints;
        [Tooltip("The patrol interval time")]
        public float patrolInterval = 1f;
        [Tooltip("The speed of patrol")]
        public float speed = 1f;

        private int _waypointIndex = 0;
        private float _patrolCounter = 0f;
        private bool _patrolIdle = false;

        public override TaskStatus OnUpdate()
        {
            if (_patrolIdle)
            {
                _patrolCounter += Time.deltaTime;
                if (_patrolCounter >= patrolInterval)
                    _patrolIdle = false;
            }
            else
            {
                Transform wp = waypoints[_waypointIndex];
                if (Vector3.Distance(transform.position, wp.position) < 0.01f)
                {
                    transform.position = wp.position;
                    _patrolCounter = 0f;
                    _patrolIdle = true;

                    _waypointIndex = (_waypointIndex + 1) % waypoints.Length;
                }
                else
                {
                    transform.position = Vector3.MoveTowards(transform.position, wp.position, speed * Time.deltaTime);
                    transform.LookAt(wp.position);
                }
            }

            return TaskStatus.Success;
        }
    }
}